package com.lysj.admin.master.bussiness.company.company.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lysj.admin.master.bussiness.admin.domain.CompanyProviderBind;
import com.lysj.admin.master.bussiness.admin.domain.ServiceProvider;
import com.lysj.admin.master.bussiness.admin.service.CompanyProviderBindService;
import com.lysj.admin.master.bussiness.admin.service.ServiceProviderService;
import com.lysj.admin.master.bussiness.company.company.domain.CommissionApply;
import com.lysj.admin.master.bussiness.company.company.domain.CommissionDetail;
import com.lysj.admin.master.bussiness.company.company.domain.Company;
import com.lysj.admin.master.bussiness.company.company.dto.CommissionApplyConditionDTO;
import com.lysj.admin.master.bussiness.company.company.dto.CompanyBaseDto;
import com.lysj.admin.master.bussiness.company.company.mapper.CommissionApplyMapper;
import com.lysj.admin.master.bussiness.company.company.service.CommissionApplyService;
import com.lysj.admin.master.bussiness.company.company.service.CommissionDetailService;
import com.lysj.admin.master.bussiness.company.company.service.CompanyService;
import com.lysj.admin.master.bussiness.company.company.vo.CommissionExcelVO;
import com.lysj.admin.master.common.CommonConstant;
import com.lysj.admin.master.common.annotation.MyList;
import com.lysj.admin.master.common.annotation.TokenInfo;
import com.lysj.admin.master.common.enumeration.EnumUtils;
import com.lysj.admin.master.common.spring.mpbase.MyController;
import com.lysj.admin.master.common.spring.mpbase.MyService;
import com.lysj.admin.master.common.web.EasyPoiUtil;
import com.lysj.admin.master.common.web.ParamUtil;
import com.lysj.admin.master.common.web.Resp;
import com.lysj.admin.master.common.web.RespUtil;
import com.lysj.admin.master.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Created by zk on 2020-01-10 15:14
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/company/commission_apply")
public class CommissionApplyController extends MyController<CommissionApplyMapper, CommissionApply, CommissionApplyConditionDTO> {

    @Resource
    private CommissionApplyService commissionApplyService;
    @Resource
    private CompanyProviderBindService companyProviderBindService;
    @Resource
    private ServiceProviderService serviceProviderService;
    @Resource
    private CommissionDetailService commissionDetailService;
    @Resource
    private CompanyService companyService;
    @Resource
    private UploadService uploadService;

    @Override
    public MyService<CommissionApplyMapper, CommissionApply> getService() {
        return commissionApplyService;
    }

    @PostMapping("/grant_order")
    public Resp grantOrder(String id, String title, String description, String standard, String contractId) {
        commissionApplyService.grantOrder(id, title, description, standard, contractId);
        return RespUtil.success("发单成功");
    }


    /*
     * @author Created by drj on 2020/1/13 10:54
     * @Description ：管理员获取发放申请
     */
    @MyList
    public Resp list(CommissionApplyConditionDTO condition) {
        Page<CommissionApply> commissionApplyPage = getService().pageList(condition);

        for (CommissionApply commissionApply : commissionApplyPage.getRecords()) {
            commissionApply.setCostStatusTxt(EnumUtils.findStatusByCode(commissionApply.getCostStatus(),
                    CommissionApply.CostStatus.class));
        }
        return RespUtil.success(commissionApplyPage);
    }


    /*
     * @author Created by drj on 2020/1/13 10:55
     * @Description :用工企业获取发放申请
     */
    @GetMapping("/find_by_company_id")
    public Resp findByCompanyId(CompanyBaseDto condition) {
        condition.setCompanyId(getJwtProperty(CommonConstant.COMPANY_ID_NAME));
        Page<CommissionApply> commissionApplyPage = getService().pageList(condition);

        for (CommissionApply commissionApply : commissionApplyPage.getRecords()) {
            commissionApply.setCostStatusTxt(EnumUtils.findStatusByCode(commissionApply.getCostStatus(),
                    CommissionApply.CostStatus.class));
        }
        return RespUtil.success(commissionApplyPage);
    }


    @PostMapping("/apply")
    public Resp apply(@TokenInfo(CommonConstant.COMPANY_ID_NAME) String companyId, String providerId, MultipartFile file) {
        CompanyProviderBind bind = companyProviderBindService.findByCompanyIdAndServiceProviderId(companyId, providerId);
        if (bind == null) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "服务商不存在");
        }
        List<CommissionExcelVO> commissionExcelVOS = EasyPoiUtil.importExcel(file, 0, 1, CommissionExcelVO.class);
        if (ParamUtil.isBlank(commissionExcelVOS)) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "请填写表格数据");
        }
        BigDecimal total = commissionExcelVOS.parallelStream()
                .filter(vo -> vo.getIdNum() != null)
                .map(CommissionExcelVO::getActPayPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        if (total.compareTo(bind.getBalance()) > 0) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "余额不足");
        }
        Company company = companyService.getById(companyId);
        //将excel上传到硬盘中,返回文件路径
//        String excelPath = uploadFileService.excelUpload(file);
        String excelPath = uploadService.upload(file).getPath();
        //获取服务商
        ServiceProvider serviceProvider = serviceProviderService.getById(bind.getServiceProviderId());
        //生成订单
        CommissionApply commissionApply = new CommissionApply();
        commissionApply.setCompanyId(companyId);
        commissionApply.setCompanyName(company.getName());
        commissionApply.setServiceProviderId(bind.getServiceProviderId());
        commissionApply.setServiceProviderName(serviceProvider.getName());
        commissionApply.setActPayPrice(total);
        commissionApply.setCostStatus(CommissionApply.CostStatus.AUDITING.getCode());
        commissionApply.setExcelPath(excelPath);
        commissionApply.setTargetType(CommissionApply.TargetType.UNKNOWN.getCode());
        this.save(commissionApply);
        //生成明细
        List<CommissionDetail> employeeList = commissionExcelVOS.parallelStream()
                .map(commissionExcelVO -> initDetail(commissionExcelVO, commissionApply.getId()))
                .collect(Collectors.toList());
        commissionDetailService.saveBatch(employeeList);
        return RespUtil.success("操作成功");
    }


    private CommissionDetail initDetail(CommissionExcelVO model, String commissionApplyId) {
        CommissionDetail commissionDetail = new CommissionDetail();
        //获取Hutool拷贝实例
        CopyOptions copyOptions = CopyOptions.create();
        //忽略为null值得属性
        copyOptions.setIgnoreNullValue(true);
        //进行属性拷贝
        BeanUtil.copyProperties(model, commissionDetail, copyOptions);
        commissionDetail.setCommissionApplyId(commissionApplyId);
        commissionDetail.setReason("");
        commissionDetail.setCommissionStatus(CommissionDetail.CommissionStatus.NO_GRANT.getCode());
        return commissionDetail;
    }


    /*
     * @author Created by drj on 2020/1/13 11:13
     * @Description :管理员审核发放申请
     */
    @PostMapping("/audit")
    public Resp audit(String id, Integer costStatus, Integer targetType) {
        commissionApplyService.audit(id, costStatus, targetType);
        return RespUtil.success("操作成功");
    }
}
